package com.boot.system.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.boot.system.entity.SysJob;
import com.boot.system.service.JobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Component
public class InitTask implements ApplicationRunner {

    private final JobService jobService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("status", 1);
        List<SysJob> taskList = jobService.getJobList(queryParam);
        if (!taskList.isEmpty()){
            for (SysJob task : taskList) {
                CronUtil.schedule(StrUtil.format("task{}", task.getId()), task.getCron(), new Task() {
                    @Override
                    public void execute() {
                        jobService.runJob(task);
                    }
                });
            }
        }
        CronUtil.setMatchSecond(true);
        CronUtil.start();
        log.info("定时任务启动完成！");
    }

}
